package test.java.demo;

import java.util.Random;

public class SumThread {
    private static double[] nums = new double[1_0000_0000];
    private static Random r = new Random();
    private static double result1 = 0.0,result2 = 0.0,result3 = 0.0;

    public static void main(String[] args) throws InterruptedException {
        SumThread.m1();
        SumThread.m2();

    }

    static {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = r.nextDouble();
        }
    }

    /**
     * 使用单线程计算
     */
    private static void m1(){
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < nums.length; i++) {
            result1 += nums[i];
        }
        System.out.println(result1);
        long endTime = System.currentTimeMillis();
        long currentTime = endTime - startTime;
        System.out.println("线程执行时间为"+currentTime);
    }

    /**
     * 使用多线程计算
     */
    private static void m2() throws InterruptedException {
        Thread thread1 = new Thread(()->{
            for (int i = 0; i < nums.length / 2; i++) {
                result2 += nums[i];
            }
        });

        Thread thread2 = new Thread(()->{
            for (int i = nums.length / 2; i < nums.length; i++) {
                result3 += nums[i];
            }
        });

        long startTime = System.currentTimeMillis();
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(result2 + result3);
        long endTime = System.currentTimeMillis();
        long currentTime = endTime - startTime;
        System.out.println("线程执行时间为"+currentTime);
    }
}
